package com.hdl.servlet.order;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.hdl.config.AlipayConfig;
import com.hdl.entity.CartItem;
import com.hdl.entity.HdlUser;
import com.hdl.entity.MallAddress;
import com.hdl.entity.MallCart;
import com.hdl.entity.MallOrder;
import com.hdl.entity.MallOrderDetail;
import com.hdl.service.AddressService;
import com.hdl.service.MallOrderService;
import com.hdl.service.impl.AddressServiceImpl;
import com.hdl.service.impl.MallOrderServiceImpl;
import com.hdl.util.SysUtil;

/**
 * 获取用户选择的地址 选择完成后要生成订单
 * @author Administrator
 *
 */
@WebServlet("/saveOrder.let")
public class SaveOrderServlet extends HttpServlet{
	
	private AddressService service = new AddressServiceImpl();
	
	private MallOrderService os = new MallOrderServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		//判断是否登陆
		HdlUser user = (HdlUser) req.getSession().getAttribute("user");
		if(user == null) {
			req.setAttribute("error", "亲亲请先登录");
			req.getRequestDispatcher("/msg.jsp").forward(req, resp);
		}
		//登陆过
		
		//获取购物车
		MallCart cart = (MallCart) req.getSession().getAttribute("cart");
		
		//获取参数
		String mallAddressId = req.getParameter("mallAddressId");
		//调用业务逻辑层方法
		MallAddress address = service.selectByAddressId(mallAddressId);//获取地址信息
		List<MallAddress> li = new ArrayList<MallAddress>();
		li.add(address);
		List<MallAddress> list = service.getAllNameByAddress(li);
		System.out.println(list.get(0).getMallAddressDetail());
		
		//创建订单对象
		MallOrder order = new MallOrder();
		//设置属性
		order.setMallOrderId(SysUtil.get());//设置id
		order.setMallOrderAddress(list.get(0).getMallAddressDetail());//设置收获地址
		order.setMallOrderDate(new Date());//设置创建时间
		order.setMallOrderName(address.getMallAddressName());//设置订单收货人的名字
		order.setMallOrderNum(SysUtil.get());//设置订单号
		order.setMallOrderPhone(user.getHdlUserPhone());//设置订单所有这的电话
		order.setMallOrderStatus(1);//未支付
		order.setUser(user);
		order.setMallOrderCash(cart.getMallCartTotal());//设置订单的总金额
		
		//创建订单详情对象
		for (CartItem item : cart.getCartItem()) {
			MallOrderDetail detail = new MallOrderDetail();//新建对象
			//设置属性
			detail.setMallOrderDetailCount(item.getNum());//设置购物项商品的数量
			detail.setMallOrderDetailId(SysUtil.get());//设置主键
			detail.setMallOrderId(order.getMallOrderId());
			detail.setProduct(item.getProduct());//设置商品
			detail.setMallOrderDetailPrice(item.getTotal());//设置购物项小计
			
			//把订单详情对象存入订单对象的集合中
			order.getList().add(detail);
		}
		
		//调用订单业务逻辑层方法
		try {
			os.saveOrder(order);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		//清空购物车
		cart.cleanCart();
		
		//把购物车在session中删除
		req.getSession().removeAttribute("cart");
		
		//获取支付的配置信息
		AlipayConfig config = AlipayConfig.getConfig();
		//发起支付
		AlipayClient alipayClient = new DefaultAlipayClient(config.getGatewayUrl(), config.getAppId(), config.getMerchantPrivateKey(), "json", config.getCharset(), config.getAlipayPublicKey(), config.getSignType());
		
		//设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(config.getReturnUrl());
		alipayRequest.setNotifyUrl(config.getNotifyUrl());

		//商户订单号，商户网站订单系统中唯一订单号，必填
		String out_trade_no = order.getMallOrderNum();
		//付款金额，必填
		String total_amount = order.getMallOrderCash().toString();
		//订单名称，必填
		String subject = order.getMallOrderId();
		//商品描述，可空
		String body = "商品";

		String json = "{\"out_trade_no\":\""+ out_trade_no +"\"," 
				+ "\"total_amount\":\""+ total_amount +"\"," 
				+ "\"subject\":\""+ subject +"\"," 
				+ "\"body\":\""+ body +"\"," 
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}";

		alipayRequest.setBizContent(json);
		AlipayResponse res=null;
		try {
			res = alipayClient.pageExecute(alipayRequest);
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		req.setAttribute("body", res.getBody());
		
		//请求转发
		req.getRequestDispatcher("/pay.jsp").forward(req, resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

}
